<?php

namespace app\api\controller;

use app\common\controller\Api;
use \app\common\model;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecordImage;
use app\common\model\CommentRule;
use think\Db;

/**
 * 行为
 */
class Behavior extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['category', 'recordMineList', 'recordMineCharts', 'iRecordList', 'iRecordCharts', 'evidence', 'check', 'editCheck'];

    /**
     * @ApiTitle    (行为分类列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/18)
     * @ApiSummary  (默认是分组显示的 student是学生评价 classes是班级评价 dorm是宿舍评价 如果不分组就是所有行为分类的列表)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/category)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 id", sample="")
     * @ApiParams   (name="group", type="int", required=false, description="是否分组显示 1是-默认 0否", sample="1")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1582076891",
    "data": {
    "student": [
    {
    "id": 5,
    "name": "学生测试1",
    "type": 4,
    "image": null,
    "selected": 1
    },
    {
    "id": 7,
    "name": "学生测试2",
    "type": 4,
    "image": null,
    "selected": 0
    },
    {
    "id": 8,
    "name": "学生测试3",
    "type": 4,
    "image": null,
    "selected": 0
    }
    ],
    "classes": [
    {
    "id": 9,
    "name": "班级测试",
    "type": 1,
    "image": null,
    "selected": 1
    },
    {
    "id": 12,
    "name": "两操评价",
    "type": 1,
    "image": null,
    "selected": 0
    },
    {
    "id": 13,
    "name": "班级测试2",
    "type": 1,
    "image": "/uploads/20200219/8284af499ea84f5bb8517c815867e7c3.jpg",
    "selected": 0
    }
    ],
    "dorm": [
    {
    "id": 10,
    "name": "宿舍1",
    "type": 2,
    "image": null,
    "selected": 0
    },
    {
    "id": 11,
    "name": "宿舍学生1",
    "type": 3,
    "image": null,
    "selected": 0
    }
    ]
    }
    })
     */
    public function category()
    {
        $school_id = $this->request->request('school_id');
        $group = $this->request->request('group', 1); //是否分组

        $list = model\BehaviorCategory::where('school_id', $school_id)
            ->where('status', model\BehaviorCategory::DISPLAY)
            ->field('id,name,type,image')->select();

        $inCommonUse = model\InCommonUse::where('user_id', $this->auth->id)
            ->column('id', 'behavior_category_id');

        $data = [];
        foreach ($list as $key => $value) {
            if (isset($inCommonUse[$value['id']])) {
                $value['selected'] = 1;
            } else {
                $value['selected'] = 0;
            }

            if ($group) {
                switch ($value['type']) {
                    case model\BehaviorCategory::CLASSES :
                        $data['classes'][] = $value;
                        break;
                    case model\BehaviorCategory::DORM :
                    case model\BehaviorCategory::DORM_STUDENT :
                        $data['dorm'][] = $value;
                        break;
                    case model\BehaviorCategory::STUDENT :
                        $data['student'][] = $value;
                        break;
                }
            } else {
                $data[] = $value;
            }
        }

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (点评我班的 列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/14)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/recordMineList)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="page", type="integer", required=true, description="页码", sample="1")
     * @ApiParams   (name="listRows", type="integer", required=true, description="每页条数 默认10", sample="")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function recordMineList()
    {
        $user_id = $this->auth->id;
        $page = $this->request->request('page', 1);
        $listRows = $this->request->request('listRows', 10);
        $time_type = $this->request->request('time_type');

        $teacher = \app\common\model\Teacher::where('user_id', $user_id)->find();
        if ($teacher) {
            $classes = \app\common\model\Classes::where('headmaster', $teacher->id)->field('id')->find();
        } else {
            $classes = \app\common\model\Classes::alias('classes')
                ->join('__STUDENT__ student', 'student.class_id = classes.id')
                ->where('student.user_id', $user_id)
                ->field('classes.id')
                ->find();
        }

        if (!$classes) {
            $data['summary']['positive_score'] = 0;
            $data['summary']['negative_score'] = 0;
            $data['summary']['student_count'] = 0;
            $data['list'] = null;
            $this->success('', $data);
        }

        if ($page < 2) {
            $data['summary'] = model\BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                ->where('detail.class_id', $classes->id)
                ->where(function ($query) use ($time_type) {
                    if ($time_type) {
                        $date = get_time($time_type, true);
                        $query->whereBetween('record.created_at', [$date['start_time'], $date['end_time']]);
                    }
                })
                ->field('COUNT(DISTINCT(record.student_id)) student_count,SUM(CASE WHEN detail.behavior_type = 1 THEN detail.score ELSE 0 END) positive_score,ABS(SUM(CASE WHEN detail.behavior_type = 2 THEN detail.score ELSE 0 END)) negative_score')
                ->find();

            $data['summary']['student_count'] = !isset($data['summary']['student_count']) ? 0 : $data['summary']['student_count'];
        }

        $data['list'] = model\BehaviorRecord::with(['details' => ['category']])
            ->where('class_id', $classes->id)
            ->where(function ($query) use ($time_type) {
                if ($time_type) {
                    $date = get_time($time_type, true);
                    $query->whereBetween('created_at', [$date['start_time'], $date['end_time']]);
                }
            })
            ->field('id,record_user_id,record_username,record_user_group,behavior_category_type,comment,created_at,json_data')
            ->order('id', 'desc')
            ->paginate($listRows);

        if ($data['list']) {
            $data['list'] = ($data['list'])->toArray();
            foreach ($data['list']['data'] as $key => $value) {
                $data['list']['data'][$key]['total_score'] = array_sum(array_column($value['details'], 'score'));
            }
        }

        $this->success('', $data);

    }

    /**
     * @ApiTitle    (点评我班的 图例)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/4/3)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/recordMineCharts)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function recordMineCharts()
    {
        $user_id = $this->auth->id;
        $time_type = $this->request->request('time_type');

        $teacher = \app\common\model\Teacher::where('user_id', $user_id)->find();
        if ($teacher) {
            $classes = \app\common\model\Classes::where('headmaster', $teacher->id)->field('id')->find();
        } else {
            $classes = \app\common\model\Classes::alias('classes')
                ->join('__STUDENT__ student', 'student.class_id = classes.id')
                ->where('student.user_id', $user_id)
                ->field('classes.id')
                ->find();
        }

        $list = BehaviorCategory::alias('category')
            ->join('__BEHAVIOR__ behavior', 'behavior.category_id = category.id')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.behavior_id = behavior.id', 'left')
            ->join('__BEHAVIOR_RECORD__ record', 'record.id = detail.record_id', 'left')
            ->where('record.record_user_id', $this->auth->id)
            ->where('record.class_id', $classes['id'])
            ->where(function ($query) use ($time_type) {
                if ($time_type) {
                    $date = get_time($time_type, true);
                    $query->whereBetween('record.created_at', [$date['start_time'], $date['end_time']]);
                }
            })
            ->field('behavior.id,behavior.name,behavior.type,sum(detail.score) score')
            ->group('behavior.id')
            ->select();

        $this->success('', $list);
    }

    /**
     * @ApiTitle    (我的点评 列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/14)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/iRecordList)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="page", type="integer", required=true, description="页码", sample="1")
     * @ApiParams   (name="listRows", type="integer", required=true, description="每页条数 默认10", sample="")
     * @ApiParams   (name="type", type="string|int", required=true, description="classes班级 student学生 dorm宿舍", sample="classes")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiParams   (name="start_time", type="string", required=false, description="自定义开始时间", sample="")
     * @ApiParams   (name="end_time", type="string", required=false, description="自定义结束时间", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function iRecordList()
    {
        $user_id = $this->auth->id;
        $page = $this->request->request('page', 1);
        $listRows = $this->request->request('listRows', 10);

        $type = $this->request->request('type', 'classes');
        $time_type = $this->request->request('time_type', 'month');

        switch ($type) {
            case 'classes':
                $key = 'class_id';
                $behavior_category_type = [BehaviorCategory::CLASSES];
                break;
            case 'student':
                $key = 'student_id';
                $behavior_category_type = [BehaviorCategory::STUDENT];
                break;
            case 'dorm':
                $key = 'dorm_id';
                $behavior_category_type = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
                break;
            default:
                return $this->error('类型错误');
        }

        $date = get_time($time_type, true);

        if ($page < 2) {
            $data['summary'] = model\BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                ->where('record.record_user_id', $user_id)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->whereBetween('record.created_at', [$date['start_time'], $date['end_time']])
                ->field("COUNT(DISTINCT(record.$key)) count,SUM(CASE WHEN detail.behavior_type = 1 THEN detail.score ELSE 0 END) positive_score,ABS(SUM(CASE WHEN detail.behavior_type = 2 THEN detail.score ELSE 0 END)) negative_score")
                ->find();
        }

        $data['list'] = model\BehaviorRecord::with(['details' => ['category']])
            ->where('record_user_id', $user_id)
            ->whereIn('behavior_category_type', $behavior_category_type)
            ->whereBetween('created_at', [$date['start_time'], $date['end_time']])
            ->field('id,record_user_id,record_username,record_user_group,behavior_category_type,comment,created_at,class_id,dorm_id,student_id,json_data')
            ->order('id', 'desc')
            ->paginate($listRows);

        if ($data['list']) {

            $data['list'] = ($data['list'])->toArray();
            $can_del = $this->auth->check('behavior/delBehaviorRecord');

            foreach ($data['list']['data'] as $key => $value) {

                switch ($value['behavior_category_type']) {
                    case BehaviorCategory::CLASSES:
                        $can_edit = $this->auth->check('classes/addBehaviorRecord');
                        break;
                    case BehaviorCategory::STUDENT:
                        $can_edit = $this->auth->check('student/addBehaviorRecord');
                        break;
                    case BehaviorCategory::DORM:
                        $can_edit = $this->auth->check('dorm/addBehaviorRecord');
                        break;
                    default:
                        $can_edit = false;
                        break;
                }

                $data['list']['data'][$key]['can_del'] = $can_del;
                $data['list']['data'][$key]['can_edit'] = $can_edit;
                $data['list']['data'][$key]['total_score'] = array_sum(array_column($value['details'], 'score'));
            }
        }

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (我的点评 图例)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/4/3)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/iRecordCharts)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="type", type="string|int", required=true, description="classes班级 student学生 dorm宿舍", sample="classes")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function iRecordCharts()
    {
        $type = $this->request->request('type', 'classes');
        $time_type = $this->request->request('time_type', 'month');

        switch ($type) {
            case 'classes':
                $behavior_category_type = [BehaviorCategory::CLASSES];
                break;
            case 'student':
                $behavior_category_type = [BehaviorCategory::STUDENT];
                break;
            case 'dorm':
                $behavior_category_type = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
                break;
            default:
                return $this->error('类型错误');
        }

        $date = get_time($time_type, true);

        $behaviors = BehaviorCategory::alias('category')
            ->join('__BEHAVIOR__ behavior', 'behavior.category_id = category.id')
            ->whereIn('category.type', $behavior_category_type)
            ->field('behavior.id,behavior.name,behavior.type,category.name category_name')
            ->select();

        if (!$behaviors) {
            $this->success();
        }

        $ret = model\BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id', 'left')
            ->whereIn('detail.behavior_id', array_column(collection($behaviors)->toArray(), 'id'))
            ->where('record.record_user_id', $this->auth->id)
            ->whereBetween('record.created_at', [$date['start_time'], $date['end_time']])
            ->group('detail.behavior_id')
            ->column('detail.behavior_id,sum(detail.score) score', 'detail.behavior_id');

        foreach ($behaviors as $key => &$behavior) {
            if (isset($ret[$behavior['id']])) {
                $behavior['score'] = $ret[$behavior['id']];
                $behavior['is_record'] = 1;
            } else {
                $behavior['score'] = 0;
                $behavior['is_record'] = 0;
            }
        }

        $this->success('', $behaviors);
    }

    /**
     * @ApiTitle    (删除点评记录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/3/5)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/delBehaviorRecord)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="记录id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function delBehaviorRecord()
    {
        $record_id = $this->request->post('id');

        $record = model\BehaviorRecord::where('id', $record_id)
            ->where('record_user_id', $this->auth->id)
            ->find();

        if (!$record) $this->error('记录不存在');

        Db::startTrans();
        try {
            $record->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage() ? $e->getMessage() : '删除失败');
        }

        $this->success('删除成功');
    }

    /**
     * @ApiTitle    (添加佐证)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/3/5)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/addEvidence)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="记录 id", sample="")
     * @ApiParams   (name="comment", type="string", required=false, description="文字说明", sample="")
     * @ApiParams   (name="images", type="string", required=false, description="图片 以英文 , 分割", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function addEvidence()
    {
        $id = $this->request->request('id', 0);
        $content = $this->request->request('content', '');
        $images = $this->request->request('images', '');

        $record_detail = model\BehaviorRecordDetail::where('id', $id)->find();
        if (!$record_detail) {
            $this->error('记录不存在');
        }
        $record = model\BehaviorRecord::where('id', $record_detail->record_id)
            ->where('record_user_id', $this->auth->id)
            ->find();
        if (!$record) {
            $this->error('记录不存在');
        }

        if ($content) {
            $record->content = $record->content . $content;
            $record->save();
        }

        if ($images) {
            $images = explode(',', $images);
            $behavior_record_image_data = [];
            foreach ($images as $key => $image) {
                $behavior_record_image_data[] = [
                    'record_id' => $record->id,
                    'record_detail_id' => $record_detail->id,
                    'url' => $image,
                ];
            }
            $behaviorRecordImage = new BehaviorRecordImage();
            $behaviorRecordImage->saveAll($behavior_record_image_data);
        }

        $this->success();
    }

    /**
     * @ApiTitle    (查看佐证)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/4/10)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/evidence)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="记录 id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function evidence()
    {
        $id = $this->request->request('id', 0);

        if ($this->auth->check('behavior/delBehaviorRecord')) {
            $record = model\BehaviorRecord::with(['details' => ['category', 'images']])
                ->where('record_user_id', $this->auth->id)
                ->where('id', $id)
                ->field('id,record_user_id,record_username,record_user_group,behavior_category_type,comment,created_at')
                ->find();

            $this->success('', $record);
        } else {
            $this->error(__('You have no permission'));
        }

    }

    /**
     * @ApiTitle    (检测当前时间点是否可点评)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/3/27)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/check)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function check()
    {
        $data = [
            'classes' => CommentRule::checkRule(BehaviorCategory::CLASSES),
            'dorm' => CommentRule::checkRule(BehaviorCategory::DORM),
        ];
        $this->success('', $data);
    }

    /**
     * @ApiTitle    (判断是否可点评、修改)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/3/27)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/editCheck)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams  (name="type", type="string", required=true, description="类型 classes=班级 dorm=宿舍 student=学生", sample="classes")
     * @ApiParams  (name="id", type="int", required=true, description="id", sample="98")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1585531342",
    "data": {
    "can_comment": true,// 是否可点评
    "can_edit": false,// 是否可修改
    "data": null// 如果 can_edit = true data会有值
    }
    })
     */
    public function editCheck()
    {
        $type = $this->request->request('type');// classes dorm student
        $id = $this->request->request('id');

        if (!$type || !$id) {
            $this->error('参数有误');
        }

        switch ($type) {
            case 'classes':
                $auth_rule = 'classes/addBehaviorRecord';
                $comment_rule = BehaviorCategory::CLASSES;
                $where = [
                    'class_id' => $id,
                    'behavior_category_type' => BehaviorCategory::CLASSES,
                ];
                break;
            case 'dorm':
                $auth_rule = 'dorm/addBehaviorRecord';
                $comment_rule = BehaviorCategory::DORM;
                $where = [
                    'dorm_id' => $id,
                    'behavior_category_type' => ['in', [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT]],
                ];
                break;
            case 'student':
                $auth_rule = 'student/addBehaviorRecord';
                $comment_rule = false;
                $where = [
                    'student_id' => $id,
                    'behavior_category_type' => BehaviorCategory::STUDENT,
                ];
                break;
            default:
                $this->error('参数有误');
                return;
        }

        if (!$this->auth->check($auth_rule)) {
            $this->error('暂无权限');
        }

        // 是否可以点评
        $can_comment = true;

        if ($comment_rule) {
            $rule = CommentRule::checkRule($comment_rule);
        }
        //$can_comment = $comment_rule ? (CommentRule::checkRule($comment_rule) ? true : false) : true;

        // 查询当天的点评记录
        $ret = model\BehaviorRecord::with('details,images')
            ->where('record_user_id', $this->auth->id)
            ->where($where)
            ->whereTime('created_at', 'today')
            ->order('id', 'desc')
            ->find();

        $data['can_comment'] = $can_comment && !$ret ? true : false;
        $data['can_edit'] = $can_comment && $ret ? true : (!$can_comment && $ret ? true : false);
        $data['data'] = $data['can_edit'] ? $ret : null;

        $this->success('', $data);
    }

}
